package com.nettest.service.demo;

import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.nettest.bean.BaseCriteriaVo;
import com.nettest.bean.usermanage.DemoCriteriaVo;
import com.nettest.dao.demo.Grid50000Dao;
import com.nettest.entity.BaseEntity;
import com.nettest.entity.demo.Grid50000;

@Service
@Transactional
public class Grid50000Service {
	@Autowired
	private Grid50000Dao grid50000Dao;

	public List<?> queryByCriteria(BaseCriteriaVo criteriaVo) throws Exception {
		Set<Criterion> set = getCriteriaSet(criteriaVo);
		
		String order = criteriaVo.getDescOrAsc();
		Set<Order> orderSet = new HashSet<Order>();
		if (order != null) {
			if ("ASC".equalsIgnoreCase(order)) {
				orderSet.add(Order.asc(criteriaVo.getDescOrAsc()));
			} else {
				orderSet.add(Order.desc(criteriaVo.getDescOrAsc()));
			}
		}
		List<?> result = grid50000Dao.query(set, orderSet,
				criteriaVo.getFirstResult(), criteriaVo.getMaxResults());
		return result;
	}

	public BaseEntity save(BaseEntity entity) throws Exception {
		return grid50000Dao.save((Grid50000)entity);
	}

	public void delete(Long id) throws Exception {
		grid50000Dao.delete(id);
	}

	public List<?> executeQuery(String sql) throws Exception {
		return grid50000Dao.findBySql(sql);
	}

	public int totalSize(BaseCriteriaVo criteriaVo) throws Exception {
		Set<Criterion> set = getCriteriaSet(criteriaVo);
		return grid50000Dao.totalSize(set);
	}

	public Grid50000 get(Serializable id) throws Exception {
		return grid50000Dao.get(id);
	}
	
	protected Set<Criterion> getCriteriaSet(BaseCriteriaVo criteriaVo) {
		Set<Criterion> set = new HashSet<Criterion>();
		DemoCriteriaVo vo = (DemoCriteriaVo)criteriaVo;
		if(vo.getItem_nm() != null) {
			set.add(Restrictions.ilike("itemName",vo.getItem_nm(),MatchMode.ANYWHERE));
		} 
		if(vo.getItem_cd() != null) {
			set.add(Restrictions.ilike("itemCd",vo.getItem_cd(),MatchMode.ANYWHERE));
		}
		return set;
	}
}
